// =================================================================================================
//
//	CopyEngine Framework
//	Copyright 2012 Eran. All Rights Reserved.
//
//	This program is free software. You can redistribute and/or modify infoTree
//	in accordance with the terms of the accompanying license agreement.
//
// =================================================================================================

package app.displayTree.analyze {
    import app.displayTree.special.SpecialSymbolManger;

    import copyengine.infoTree.meta.CESDisplayObjectMeta;

    import flash.display.DisplayObject;
    import flash.display.MovieClip;
    import flash.display.Sprite;

    import org.as3commons.lang.StringUtils;

    /**
     * 用于检测某一个Mc是否可以忽略内部解析 直接作为一个整体直接Cache
     *
     * 1· 当给定的Mc不是SpecialMc
     * 2· 其内部所有的Child均以instance开头 及用户没有对任何一个Child起别名
     *
     * 则该Mc直接忽略其内部的递归直接对其整体进行Cache,从而增加渲染性能
     */
    public final class FlattenSpriteTester {

        private var mSpecialSymbolManger:SpecialSymbolManger;
        private var mSupport:DisplayTreeAnalyzeSupport;

        public function FlattenSpriteTester() {
        }

        public function initialize(_manger:SpecialSymbolManger, _support):void {
            mSpecialSymbolManger = _manger;
            mSupport = _support;
        }

        public function isCanFlattenSprite(_sp:Sprite):Boolean {
            return checkTarget(_sp);
        }

        private function checkTarget(_target:DisplayObject):Boolean {
            //if (StringUtils.startsWith(_target.name, "instance"))
            if (_target is MovieClip) {
                if ((_target as MovieClip).totalFrames == 1) {
                    var spTarget:Sprite = _target as Sprite;
                    var specialMeta:CESDisplayObjectMeta = mSpecialSymbolManger.tryToGenerateSpecialSymbolMeta(spTarget, mSupport);
                    if (specialMeta) {
                        //当前是SpecialMeta,不可以Flatten
                        return false;
                    }
                    else {
                        var totalNumChild:int = spTarget.numChildren;
                        for (var i:int = 0; i < totalNumChild; i++) {
                            //当前节点下的子节点如果设置过Name,则当前节点不能Flatten
                            if (!StringUtils.startsWith(spTarget.getChildAt(i).name, "instance") || !checkTarget(spTarget.getChildAt(i))) {
                                return false;
                            }
                        }
                        return true;
                    }
                }
                else {
                    //递归中检查出MovieClip则不可以Flatten
                    return false;
                }
            }
            else {
                //不是MovieClip也不是Sprite 且名字是默认的 则可以Flatten
                return StringUtils.startsWith(_target.name, "instance")
            }
        }


    }
}
